#!/usr/bin/env python
#import datetime
import json
import pika
import ConfigParser
import logging
#import socket

from datetime import datetime

def send_measurement(value):

    # slurp in the configfile
    config = ConfigParser.RawConfigParser()
    config.readfp(open('smogsettings.cfg'))
    
    # establish connection to broker
    server = config.get('server', 'serverhost')
    connection = pika.BlockingConnection(pika.ConnectionParameters(server))
    
    queue = config.get('server', 'queue')
    channel = connection.channel()
    channel.queue_declare(queue)

    # we append 'Z' to the time string because the datetime lib
    # from python doesn't honor the ISO8601 format
    time = datetime.utcnow().isoformat() + 'Z'

    # We construct a dictionary, pythons key-value-map
    data = {
      'sensor_id': config.get('sensorunit', 'sensorid'),
      'longitude' :config.get('sensorunit', 'longitude'),
      'latitude': config.get('sensorunit', 'latitude'),
      'location': config.get('sensorunit', 'location'),
      'time': time,
      'value': value,
      'type': config.get('sensorunit', 'measurementType')
    }
  
    # Convert the dictionary "data" into a json-string
    json_string = json.dumps(data, indent=2)
    print "Jsondata: ", json_string

    # send information and close connection
    channel.basic_publish(exchange = '', routing_key = queue, body = json_string)
    connection.close()

## "main programm" just for testing purposes :-)
logging.basicConfig(level=logging.INFO)
send_measurement(12)

